﻿using BLL;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using webui.Models;
using webui.ViewModel;
using Tools;
using SqlSugar;

namespace webui.Areas.Admin.Controllers
{
    public class RoleController : Controller
    {
        public RoleInfoBLL iroleblll = new RoleInfoBLL();
        public RolePermissionBLL irolepermissbll = new RolePermissionBLL();

        public PermissionBLL ipermissbll = new PermissionBLL();

        /// <summary>
        /// 显示 角色视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 加载 角色数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            //0.接收参数 page=1&rows=5
            int pageIndex = int.Parse(form["page"]);
            int pageSize = int.Parse(form["rows"]);

            //1.读取数据 
            PageModel page = new PageModel()
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                PageCount=0 
            };
            var list = iroleblll.GetPageList(r => r.isDel == false, page, p => p.id, OrderByType.Desc);
             
             //2.将list转成 json 字符串发回浏览器
            return Json(new DataGridModel() { rows = list, total = page.PageCount });
        }

        /// <summary>
        /// 显示添加角色页面
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        [HttpGet]
        public ActionResult AddRole()
        {
            return PartialView("EditRole");
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddRole(RoleInfo model)
        {
            model.isDel = false;
            model.isShow = true;
            model.addtime = DateTime.Now;
            iroleblll.Insert(model);
            RoleInfo rmodel = iroleblll.GetList(p => p.isDel == false).FirstOrDefault();
            RolePermission Muserrole = new RolePermission() { addtime = model.addtime, isDel = false, pId = 2, rid = rmodel.id }; //添加跟目录权限
            irolepermissbll.Insert(Muserrole);
            return Redirect("/admin/role/index");

        }

        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult EditRole(int id)
        {
            RoleInfo model = iroleblll.GetList(p => p.id == id).FirstOrDefault();
            V_Role vModel = model.MapTo<V_Role, RoleInfo>();
            return PartialView(vModel);
        }

        /// <summary>
        /// 保存修改的角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditRole(RoleInfo model)
        {
            iroleblll.Update(u => new RoleInfo { rName = model.rName, remark = model.remark }, u => u.id == model.id);
            return Redirect("/admin/role/index");
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult delrole(int id)
        {
            try
            {
                iroleblll.DeleteById(id);
            }
            catch (Exception ce)
            {

                return OperateContext.Current.RedirectAjax("err", "删除失败，请检查是否有关联权限，或角色没删除~", null, "");
            }
             
            return OperateContext.Current.RedirectAjax("ok", "删除成功~~~", null, "");
        }



        /// <summary>
        /// 3.0 加载 所有的权限树（把角色对应的权限选中）
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetRoleTree(int id)
        {
         
            //准备一个 角色id，传给视图
            ViewBag.roleId = id; 
            return PartialView( );
        }


     
     


        /// <summary>
        /// 3.0 加载 所有的权限树（把角色对应的权限选中）
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns> 
        [SkipPemission]
        public ActionResult GetTreeJson(int roleid)
        {
            //int roleid = sroleid.ToInt();
            List<V_ThreeNode> tree = new List<V_ThreeNode>();
            tree.Add(new V_ThreeNode());
            tree[0].id = 2; //数据库等于2，保持一致
            tree[0].text = "后台菜单管理";
            tree[0].children = new List<V_ThreeNode>();
            var allList = ipermissbll.GetList(p => p.pIsDel == false).ToList();   // 所有 权限 
            List<Permission> parentList = (from p in allList where p.pParent == 2 select p).ToList(); //父 权限集合
            List<RolePermission> RolePList = irolepermissbll.GetList(u=> u.rid==roleid);   //1.获取角色 权限

            foreach (var item in parentList)
            {
                V_ThreeNode temTree = new V_ThreeNode()
                {
                    id = item.Id,
                    text = item.pName
                };
                var ischeck= RolePList.Where(u => u.pId == item.Id).FirstOrDefault();
                

                List<Permission> sonTree = allList.Where(u => u.pParent == item.Id).ToList();
                if (sonTree != null && sonTree.Count > 0)
                {
                    temTree.children = new List<V_ThreeNode>();
                    foreach (var item2 in sonTree)
                    {
                        V_ThreeNode temTree2 = new V_ThreeNode()
                        {
                            id = item2.Id,
                            text = item2.pName
                        };

                        var ischeck2 = RolePList.Where(u => u.pId == item2.Id).FirstOrDefault();
                        if (ischeck2 != null)
                        {
                            temTree2.Checked = true;
                        }
                         
                        temTree.children.Add(temTree2);
                    }
                }
                tree[0].children.Add(temTree);
            }
           


            return Content(tree.ToJson().Replace("C", "c").Replace("\\", "")) ;


        }


        /// <summary>
        /// 设置角色权限
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxRequest]
        public ActionResult SetRolePer()
        {
            try
            {
                //1.获取角色id
                int roleId = int.Parse(Request.Form["rid"]);
                //2.获取新的权限 id字符串
                string[] perIds = Request.Form["roleids"].Split(new string[1] { "," }, StringSplitOptions.RemoveEmptyEntries);

                //方式一 简单方式：先到角色权限表 里 把该角色 所有权限删除，然后再 把新的权限 加进去
                //方式二 麻烦方式：
                //2.1原来的所有权限旧 1,2,3,4,5

                var listOldPer = irolepermissbll.GetList(u=> u.rid==roleId).Select(r => r.pId).ToList();

                //2.2新权限  新 1，2,4,6 
                List<string> listNewPer = perIds.ToList();

                //2.3将两个集合中 相同的元素 都删除，之后，新权限集合里的权限就是要新增到数据库的，旧权限集合里的权限 就是要从数据库删除的
                for (int i = listOldPer.Count - 1; i >= 0; i--)
                {
                    int old = listOldPer[i];
                    if (listNewPer.Contains(old.ToString()))
                    {
                        listOldPer.Remove(old);
                        listNewPer.Remove(old.ToString());
                    }
                }
                //2.4新增新的权限
                listNewPer.ForEach(newP =>
                {
                    
                    irolepermissbll.Insert(new RolePermission() { rid = roleId, pId = int.Parse(newP), addtime = DateTime.Now, isDel = false });
                });
                //3.5移除旧的权限
                listOldPer.ForEach(oldP =>
                {
                    irolepermissbll.Delete(p => p.rid == roleId && p.pId == oldP);
                });
            }
            catch (Exception ex)
            {
                return OperateContext.Current.RedirectAjax("err", "异常：" + ex.Message, null, "");
            }
            return OperateContext.Current.RedirectAjax("ok", "修改权限成功~~~！", null, "");
        }


    }
}